package com.zml.pdf.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zml.pdf.entity.Pdfs;
import com.zml.pdf.entity.SearchReqVo;
import com.zml.pdf.entity.SearchResultEntity;
import com.zml.pdf.exception.*;
import com.zml.pdf.service.PdfService;
import com.zml.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
//import org.apache.commons.io.IOUtils;
//import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
//import org.apache.tomcat.util.http.fileupload.FileItem;
//import org.apache.tomcat.util.http.fileupload.FileItemFactory;
//import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;


@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/pdfapi")
@Api(tags = "PDF管理中心Controller")
public class pdfController {

    @Autowired
    private PdfService pdfService;
    private Logger log = LoggerFactory.getLogger(pdfController.class);

    /**
     * 上传
     *
     * @param file
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "保存PDF文件接口", notes = "保存PDf文件，并对PDF文件进行切分，加密，其中每十页一个分片.", response = SimpleResult.class)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public SimpleResult save(@RequestParam("file") MultipartFile file) {
        log.info("开始保存文件信息！");
        Pdfs p = new Pdfs();
        if (!file.isEmpty()) {
            try {
                String fileName = file.getOriginalFilename();
                if (!PdfUtil.valid(fileName)) {
                    return new SimpleResult("9999", "文件类型不正确！");
                }
                p = PdfUtil.getPdfs();
                handlePdfFile(file, p);
                pdfService.insertPdf(p);
                log.info("成功插入记录到数据库！");
                return new SimpleResult("0000", "保存成功！");
            } catch (Exception e) {
                log.info("保存源文件失败！");
                e.printStackTrace();
                pdfService.deletePdf(p.getId());
                return new SimpleResult("9999", "保存文件失败！");
            }
        } else {
            return new SimpleResult("0000", "请上传文件！");
        }
    }


    /**
     * 上传
     *
     * @param file
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "保存PDF文件接口", notes = "保存PDf文件，并对PDF文件进行切分，加密，其中每十页一个分片.", response = SimpleResult.class)
    @RequestMapping(value = "/saveAsync", method = RequestMethod.POST)
    @ResponseBody
    public SimpleResult saveAsync(@RequestParam("file") MultipartFile file) {
        log.info("开始保存文件信息！");
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            if (!PdfUtil.valid(fileName)) {
                return new SimpleResult("9999", "文件类型不正确！");
            }
            Pdfs p = PdfUtil.getPdfs();

            Runnable r = () -> {
                try {
                    handlePdfFile(file, p);
                    pdfService.insertPdf(p);
                    log.info("成功插入记录到数据库！");
                } catch (Exception e) {
                    log.info("保存源文件失败！");
                    e.printStackTrace();
                    pdfService.deletePdf(p.getId());
                }
            };
            Thread t = new Thread(r);
            t.start();
            return new SimpleResult("0000", "上传成功，文件保存中......");
        } else {
            return new SimpleResult("0000", "请上传文件！");
        }
    }

    /**
     * 批量上传
     *
     * @param folder
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "批量保存文件夹下面所有PDF文件接口", notes = "保存PDf文件，并对PDF文件进行切分，加密，其中每十页一个分片.", response = SimpleResult.class)
    @RequestMapping(value = "/pathSave", method = RequestMethod.POST)
    @ResponseBody
    public SimpleResult pathSave(@RequestBody String path) {
    	JSONObject jsonobject = JSONObject.parseObject(path);
		String folders = jsonobject.getString("path");
		 int count = 0;
        log.info("开始保存文件夹信息！");
        File file = new File(folders);
        File[] files = file.listFiles();
        readfile(files);
        if (files != null && files.length > 0) {
        	
            for(File f:files){	
                if (!PdfUtil.valid( f.getName())) {
                    continue;
                }
                Pdfs p = PdfUtil.getPdfs();
                
                boolean b = handlePdfFile1(f, p);
                if (b) {
                    pdfService.insertPdf(p);
                    log.info("插入一条记录到数据库！");
                    count++;
                } else {
                    pdfService.deletePdf(p.getId());
                }
            }
            return new SimpleResult("0000", String.format("%d个文件上传成功，%d个文件上传失败！", count, files.length - count));
        }
        else{
        	return new SimpleResult("0000", "请选择文件！");
        }

    }
    

    

    /**
     * 批量上传
     *
     * @param folder
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "批量保存PDF文件接口", notes = "保存PDf文件，并对PDF文件进行切分，加密，其中每十页一个分片.", response = SimpleResult.class)
    @RequestMapping(value = "/batchSave", method = RequestMethod.POST)
    @ResponseBody
    public SimpleResult batchSave(@RequestParam("folder") MultipartFile[] folder) {
        log.info("开始保存文件夹信息！");
        int count = 0;
        if (folder != null && folder.length > 0) {
            for (int i = 0; i < folder.length; i++) {
                if (!PdfUtil.valid(folder[i].getOriginalFilename())) {
                    continue;
                }
                Pdfs p = PdfUtil.getPdfs();
                boolean b = handlePdfFile(folder[i], p);
                if (b) {
                    pdfService.insertPdf(p);
                    log.info("插入一条记录到数据库！");
                    count++;
                } else {
                    pdfService.deletePdf(p.getId());
                }
            }
            return new SimpleResult("0000", String.format("%d个文件上传成功，%d个文件上传失败！", count, folder.length - count));
        } else {
            return new SimpleResult("0000", "请选择文件！");
        }
    }

    @ApiOperation(value = "获取PDF列表接口", notes = "获取PDF列表，返回接口中，data对象为一个JSON数组", response = ResultWithObject.class)
    @RequestMapping(value = "/getPdfs", method = RequestMethod.POST)
    @ResponseBody
    public ResultWithObject getPdfs(HttpServletResponse response) {
        log.info("开始获取Pdf列表！");
        try {
            List<Pdfs> ppd = pdfService.getPdf();
            JSONArray jsonarray = new JSONArray();
            for (Pdfs pss : ppd) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", pss.getId());
                jsonObject.put("time", pss.getTime());
                jsonObject.put("name", pss.getName());
                jsonObject.put("totalPageNum", pss.getTotalPageNum());
//                jsonObject.put("path", pss.getpath());
//                jsonObject.put("pdfurl", pss.getpdfurl());
//                jsonObject.put("jsonurl", pss.getjsonurl());
//                jsonObject.put("openkey", pss.getopenkey());
//                jsonObject.put("splitnum", pss.getsplitnum());
                jsonarray.add(jsonObject);
            }
            return ResultWithObject.successResponse(jsonarray, "获取列表成功!", (long) jsonarray.size());
//            String aeskey = pdfService.getAESkey();
//            String EncryptContents = AESUtil.encrypt(jsonarray.toString(), aeskey);
//            response.setContentType("application/json");
//            response.setCharacterEncoding("UTF-8");
//            response.getWriter().println(EncryptContents);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResultWithObject.errorResponse("获取列表失败！");
//
        }
    }



    @ApiOperation(value = "创建资源息文件接口", notes = "创建资源息，返回接口中，data对象为一个JSON数组", response = ResultWithObject.class)
    @RequestMapping(value = "/createResourceFile", method = RequestMethod.POST)
    @ResponseBody
    public ResultWithObject createResourceFile(HttpServletResponse response) {
        log.info("开始获取Pdf列表！");
        try {
            List<Pdfs> ppd = pdfService.getPdf();
            JSONObject jsonResult = new JSONObject();
            JSONArray jsonarray = new JSONArray();
            for (Pdfs pss : ppd) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("localid", pss.getId());
                jsonObject.put("resourcename", pss.getName());
                jsonObject.put("num", pss.getTotalPageNum());
                jsonObject.put("resourceid","");
                jsonarray.add(jsonObject);
             
            }
            jsonResult.put("result",jsonarray);
            File resFile = FileUtils.getFile("PdfFiles");
            if (!resFile.exists()) {
                resFile.mkdirs();
            }
            Path sourcePath = Paths.get(resFile.getAbsolutePath(),"resourcelist.json");
            String jsonFilePath = sourcePath.toString();          
            resourcelistJsonFile(jsonFilePath,jsonResult);

            return ResultWithObject.successResponse("", "创建资源文件成功!");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResultWithObject.errorResponse("创建资源文件失败！");
//
        }
    }

    @ApiOperation(value = "创建解密信息文件接口", notes = "创建解密信息，返回接口中，data对象为一个JSON数组", response = ResultWithObject.class)
    @RequestMapping(value = "/createPdfKeytFile", method = RequestMethod.POST)
    @ResponseBody
    public ResultWithObject createPdfKeytFile(HttpServletResponse response) {
        log.info("开始获取Pdf列表！");
        try {
            List<Pdfs> ppd = pdfService.getPdf();
            JSONObject jsonKeyResult = new JSONObject();
            JSONArray jsonarrayKey = new JSONArray();
            for (Pdfs pss : ppd) {
       
                //处理解密字符串
                JSONObject jsonObjectKey = new JSONObject();
                Pdfs pdfs = pdfService.getPdfById(pss.getId());
                if (pdfs == null) {
                	jsonObjectKey.put("localid",  pss.getId());
                	jsonObjectKey.put("resourcename", pss.getName().replace(".pdf", ""));
                	jsonObjectKey.put("openKey",  "");
                }
                else
                {
                	String encryptContents = StrAESUtil.encrypt(StringUtils.reverse(pdfs.getOpenKey()), Constant.KEY);
                	encryptContents = encryptContents.replaceAll(System.lineSeparator(), "");
                	jsonObjectKey.put("localid",  pss.getId());
                	jsonObjectKey.put("resourcename", pss.getName().replace(".pdf", ""));
                	jsonObjectKey.put("openKey",  encryptContents);
                }
                jsonarrayKey.add(jsonObjectKey);
            }
            jsonKeyResult.put("data",jsonarrayKey);
            File resFile = FileUtils.getFile("PdfFiles");
            if (!resFile.exists()) {
                resFile.mkdirs();
            }
        
            //
            Path openKeyPath = Paths.get(resFile.getAbsolutePath(),"getPdfKey.json");
            String jsonFilePath = openKeyPath.toString();          
            resourcelistJsonFile(jsonFilePath,jsonKeyResult);
            
            return ResultWithObject.successResponse("", "创建文件成功!");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResultWithObject.errorResponse("创建文件失败！");
//
        }
    }

    
    
    @ApiOperation(value = "根据文件ID，获取PDF文件的密钥", notes = "返回的密钥是结果AES加密的，并用十六进制字符串表示", response = ResultWithString.class)
    @PostMapping("/getPdfKey/{id}")
    @ResponseBody
    public ResultWithString getKeyOfPdf(@PathVariable("id") String id) {
        log.info("开始获取Pdf密码！");
        log.info(id);
        try {
            Pdfs pdfs = pdfService.getPdfById(id);
            if (pdfs == null) {
                return ResultWithString.errorResponse("该文件不存在！");
            }
            String encryptContents = StrAESUtil.encrypt(StringUtils.reverse(pdfs.getOpenKey()), Constant.KEY);
            return ResultWithString.successResponse(encryptContents.replaceAll(System.lineSeparator(), ""), "获取密码成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultWithString.errorResponse("获取密码失败！");
        }
    }


    @ApiOperation(value = "根据ID获取某一个PDF文件某一页", notes = "其中ID和page参数均在url倒数第二位和倒数第一位！", response = InputStream.class)
    @GetMapping("/getPdfFile/{id}/{page}")
    public void getFile(@PathVariable("id") String id, @PathVariable("page") String page, HttpServletRequest request, HttpServletResponse response) {
        log.info("正在获取的文件ID：" + id);
        log.info("正在获取的文件页数：" + page);
        Pdfs p = pdfService.getPdfById(id);
        File file;
        if (page.equals("-1")) {
            file = new File(p.getJsonUrl());
            log.info(p.getJsonUrl());
        } else {
            int partNo = Integer.parseInt(page) / 10;
            String partFileName = partNo + "_" + Paths.get(p.getPdfUrl()).getFileName().toString();
            file = Paths.get(p.getPath(), partFileName).toFile();
            log.info(partFileName);
            response.setContentType("application/pdf;charset=UTF-8");
        }


        try {
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            if (!file.exists()) {
                outputStream.write("文件不存在".getBytes("UTF-8"));
            } else {
                InputStream in = new FileInputStream(file);
                byte[] buff = new byte[1024];
                int n;
                while ((n = in.read(buff)) != -1) {
                    outputStream.write(buff, 0, n);
                }
                in.close();
            }
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "根据ID获取某一个PDF文件某一个分片", notes = "其中ID和part参数均在url倒数第二位和倒数第一位！", response = InputStream.class)
    @GetMapping("/getPdfFilePart/{id}/{part}")
    public void getFilePart(@PathVariable("id") String id, @PathVariable("part") String part, HttpServletRequest request, HttpServletResponse response) {
        log.info("正在获取的文件ID：" + id);
        log.info("正在获取的文件分片：" + part);
        Pdfs p = pdfService.getPdfById(id);
        File file;
        if (part.equals("-1")) {
            file = new File(p.getJsonUrl());
            log.info(p.getJsonUrl());
        } else {
            int partNo = Integer.parseInt(part);
            String partFileName = partNo + "_" + Paths.get(p.getPdfUrl()).getFileName().toString();
            file = Paths.get(p.getPath(), partFileName).toFile();
            log.info(partFileName);
            response.setContentType("application/pdf;charset=UTF-8");
        }


        try {
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            if (!file.exists()) {
                outputStream.write("文件不存在".getBytes("UTF-8"));
            } else {
                InputStream in = new FileInputStream(file);
                byte[] buff = new byte[1024];
                int n;
                while ((n = in.read(buff)) != -1) {
                    outputStream.write(buff, 0, n);
                }
                in.close();
            }
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "删除文件", notes = "", response = void.class)
    @PostMapping("/deletePdfFile/{id}")
    public SimpleResult deleteFile(@PathVariable("id") String id) {
        log.info("正在获取的文件ID：" + id);
        Pdfs p = pdfService.getPdfById(id);
        if (p == null) {
            return new SimpleResult("9999", "记录不存在！");
        }

        System.out.println("删除的文件：" + p.getName());
        PdfUtil.deleteFile(p.getPath());
        PdfUtil.deleteFile(p.getPdfUrl());
        pdfService.deletePdf(p.getId());
        return new SimpleResult("0000", "删除成功！");

    }


    @ApiOperation(value = "获取加密的密钥", notes = "需要实用这个密钥对PDF文件密码进行AES解密", response = ResultWithString.class)
    @RequestMapping(value = "/getKey", method = RequestMethod.POST)
    public ResultWithString getkey(HttpServletResponse response) {
        log.info("正在获取的密码密钥……");
        try {
            return ResultWithString.successResponse(Constant.KEY, "获取密钥成功！");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            return ResultWithString.errorResponse("获取密钥失败！");
        }
    }

    @ApiOperation(value = "根据ID获取某一个PDF文件某一页", notes = "其中ID和page参数均在url倒数第二位和倒数第一位！", response = InputStream.class)
    @RequestMapping(value = "/searchFile", method = RequestMethod.POST)
    public ResultWithList searchFile(@RequestBody SearchReqVo reqVo) {
        if (reqVo == null) {
            return ResultWithList.errorResponse("请求参数为空！");
        }
        log.info("正在获取的文件ID：" + reqVo.getId());
        Pdfs p = pdfService.getPdfById(reqVo.getId());
        if (p == null) {
            return ResultWithList.errorResponse("文件不存在！");
        }
        if (StringUtils.isBlank(p.getJsonUrl())) {
            return ResultWithList.errorResponse("文件不支持全文搜索！");
        }
        String jsonFilePath = p.getJsonUrl();
        File file = new File(jsonFilePath);
        log.info(jsonFilePath);

        try {
            List<SearchResultEntity> list = new ArrayList<>();
            String str = FileUtils.readFileToString(file, "UTF-8");
            JSONArray array = JSONArray.parseArray(str);

            for (int i = 0; i < array.size(); i++) {
                String pageStr = array.getString(i);
                List<String> listSearch = getSearchResult(pageStr, reqVo.getSearchWord());
                if (listSearch == null || listSearch.size() == 0) {
                    continue;
                }
                for (String s : listSearch) {
                    SearchResultEntity entity = new SearchResultEntity();
                    entity.setPageNo(i + 1);
                    entity.setSearchStr(s);
                    list.add(entity);
                }
            }
            return ResultWithList.successResponse(list, "查询成功！", (long) list.size());
        } catch (IOException e) {
            e.printStackTrace();
            return ResultWithList.errorResponse("文件读取失败！");
        }
    }


    @ApiOperation(value = "获取文件书签", notes = "", response = void.class)
    @PostMapping("/getBookMark/{id}")
    public ResultWithList getBookMark(@PathVariable("id") String id) {

        log.info("正在获取书签的文件ID：" + id);
        Pdfs p = pdfService.getPdfById(id);
        List<BookMarkEntity> bookList = PdfUtil.getPdfBookMark(p.getPdfUrl());
        return ResultWithList.successResponse(bookList, "获取成功", (long) bookList.size());

    }

    /**
     * 保存书签
     * @param filePath
     * @return
     */
    public static boolean createMarksJsonFile(String filePath) {


        
        boolean flag = true;
        Path path = Paths.get(filePath);
        String onlyName = PdfUtil.getOnlyName(path);
        Path jsonFilePath = Paths.get(path.getParent().toString(), onlyName, onlyName  + "_bookmarks.json");
        System.out.println("保存书签路径：" + jsonFilePath);

        List<BookMarkEntity> bookList = PdfUtil.getPdfBookMark(filePath);



        JSONArray jsonObjectMarks = JSONArray.parseArray(JSON.toJSONString(bookList));
        String jsonString = jsonObjectMarks.toString();


        try {
            File file = new File( jsonFilePath.toString());
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            //  jsonString = jsonString.replaceAll("\",", "\",\r\n");
            Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(jsonString);
            write.flush();
            write.close();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 保存书签
     * @param filePath
     * @return
     */
    public static boolean resourcelistJsonFile(String jsonFilePath, JSONObject jsonObject ) {

    	boolean flag = true;
        System.out.println("创建资源解密文件：" + jsonFilePath);
        String jsonString = jsonObject.toString();
        try {

            File file = new File( jsonFilePath.toString());
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            //  jsonString = jsonString.replaceAll("\",", "\",\r\n");
            Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(jsonString);
            write.flush();
            write.close();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 对MultipartFile文件进行保存、切片加密、文字抽取操作
     * @param file
     * @param p
     * @return
     */
    private boolean handlePdfFile(MultipartFile file, Pdfs p) {

        try {
            log.info("正在保存源文件");
            p.setName(file.getOriginalFilename());
            file.transferTo(Paths.get(p.getPdfUrl()));
            log.info("正在切分的文件：" + p.getName());
            int totalPageNum = Splite.partitionPdfFile(p.getPdfUrl(), StringUtils.reverse(p.getOpenKey()));
            p.setTotalPageNum(totalPageNum);
            log.info("正在提取PDF文件文字");
            boolean b = ReadPdf.readPdf(p.getPdfUrl());
            if (!b) {
                log.info("Pdf无法提取文字！");
                p.setJsonUrl(null);
            }
            log.info("正在提取书签！");
            createMarksJsonFile(p.getPdfUrl());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            PdfUtil.deleteFile(p.getPdfUrl());
            PdfUtil.deleteFile(p.getPath());
            return false;
        }

    }
    

    /**
     * 对File文件进行保存、切片加密、文字抽取操作
     * @param file
     * @param p
     * @return
     */
    private boolean handlePdfFile1(File file, Pdfs p) {

        try {
            log.info("正在保存源文件");
            p.setName(file.getName());
            File dest = new File(p.getPdfUrl());
            copyFileUsingFileStreams(file,dest);
            
            log.info("正在切分的文件：" + p.getName());
            int totalPageNum = Splite.partitionPdfFile(p.getPdfUrl(), StringUtils.reverse(p.getOpenKey()));
            p.setTotalPageNum(totalPageNum);
            log.info("正在提取PDF文件文字");
            boolean b = ReadPdf.readPdf(p.getPdfUrl());
            if (!b) {
                log.info("Pdf无法提取文字！");
                p.setJsonUrl(null);
            }
            log.info("正在提取书签！");
            createMarksJsonFile(p.getPdfUrl());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            PdfUtil.deleteFile(p.getPdfUrl());
            PdfUtil.deleteFile(p.getPath());
            return false;
        }

    }

	private  void copyFileUsingFileStreams(File source, File dest) throws IOException {    
	    InputStream input = null;    
	    OutputStream output = null;    
	    try {
	           input = new FileInputStream(source);
	           output = new FileOutputStream(dest);        
	           byte[] buf = new byte[1024];        
	           int bytesRead;        
	           while ((bytesRead = input.read(buf)) > 0) {
	               output.write(buf, 0, bytesRead);
	           }
	    } finally {
	        input.close();
	        output.close();
	    }
	}

    /**
      * @Description: 获取字符串的针对word的搜索结果。
      * @AuthorOrModify: ye.ming
      * @Date: 19/12/6
      */
    private List<String> getSearchResult(String originStr, String searchWord) {

        List<String> result = new ArrayList<>();
        int wordLen = searchWord.length();
        if (!originStr.contains(searchWord)) {
            return result;
        }
        String[] split = originStr.split(searchWord);
        int strLen = split.length;
        int total = 0;
        for (int i = 0; i < strLen - 1; i++) {
            int l1 = split[i].length();
            total += l1;
            String start = getSub(originStr.substring(0, total), false);
            total += wordLen;
            String end = getSub(originStr.substring(total), true);
            String resultStr = "……" + start + searchWord + end + "……";

            if (i == 0 && split[0].equals("")) {
                resultStr = resultStr.replaceFirst("……", "");
            }
            result.add(resultStr);
        }
        if (originStr.endsWith(searchWord)) {
            String sub = getSub(originStr.substring(0, originStr.lastIndexOf(searchWord)), false);
            String resultStr = "……" + sub + searchWord;
            resultStr = resultStr.replaceAll(searchWord, "[" + searchWord + "]");
            result.add(resultStr);
        }
        return result;

    }

    private String getSub(String str, boolean startOrEnd) {
        return getSub(str, 30, startOrEnd);
    }

    private String getSub(String str, int length, boolean startOrEnd) {
        int len = str.length();
        if (str == null) {
            return "";
        }
        if (len <= length) {
            return str;
        } else {
            if (startOrEnd) {
                return str.substring(0, length);
            } else {
                return str.substring(len - length);
            }
        }
    }

    public static void readfile(File[] files) {
    	if (files == null) {// 如果目录为空，直接退出
    		return;
    	}
    	for(File f:files) {
	    	//如果是文件，直接输出名字
	    	if(f.isFile()) {
	    		System.out.println(f.getName());
	    	}
	    	//如果是文件夹，递归调用
	    	else if(f.isDirectory()) {
	    		readfile(f.listFiles());
	    	}
    	}
    }   

}
